import { Controller, Sse, Post, Body } from '@nestjs/common';
import { SSEService } from './sse.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface SSEEvent {
  data: string;
  id?: string;
  type?: string;
  retry?: number;
}

@Controller('sse')
export class SSEController {
  constructor(private readonly sseService: SSEService) {}

  @Sse('data')
  events(): Observable<SSEEvent> {
    return this.sseService.getEventStream().pipe(
      map((data) => ({
        data: JSON.stringify(data),
        id: String(Date.now()),
        type: 'message',
        retry: 10000,
      })),
    );
  }

  @Post('increment')
  increment() {
    return this.sseService.increment();
  }

  @Post('reset')
  reset() {
    return this.sseService.reset();
  }

  @Post('set-interval')
  setInterval(@Body() body: { interval: number }) {
    return this.sseService.setInterval(body.interval);
  }
}
